<template>
	<view style="padding-top:80rpx;box-sizing: border-box;">
		<view class="header">
			<head-children :isBack="'1'">
				<template v-slot:default="">
					<view class="time">{{ formatTime(countDown) }}</view>
					<view class="btn" @click.stop="btnSubmit">
						<image class="jiao" src="../../static/confirm.png" mode="widthFix"></image>
						<view class="">
							交卷
						</view>
					</view>
				</template>
			</head-children>
		</view>

		<view class="main">
			<view class="subject">
				<text class="type" v-if="!currentData.answer_c">判断题</text>
				<text class="type" v-if="currentData.answer_c && currentData.right_answer.length==1">选择题</text>
				<text class="type" v-if="currentData.answer_c && currentData.right_answer.length>1">多选题</text>
				{{currentData.questions}}
			</view>
			<view class="images" v-if="currentData.questions_image">
				<image class="img" :src="currentData.questions_image" mode="widthFix"></image>
			</view>
			<view class="answer">
				<view class="item" :class="correct.indexOf('A')>-1?'true':error.indexOf('A')>-1?'false':''"
					@click="handleAnswer('A')">
					<text class="round" v-if="error.indexOf('A')>-1"><u-icon name="close" color="#fff"
							size="28"></u-icon></text>
					<text class="round" :class="multipleAnswer.indexOf('A')>-1?'selected':''" v-else>A</text>
					<text class="answer-text"> {{currentData.answer_a}}</text>
				</view>
				<view class="item" :class="correct.indexOf('B')>-1?'true':error.indexOf('B')>-1?'false':''"
					@click="handleAnswer('B')">
					<text class="round" v-if="error.indexOf('B')>-1"><u-icon name="close" color="#fff"
							size="28"></u-icon></text>
					<text class="round" :class="multipleAnswer.indexOf('B')>-1?'selected':''" v-else>B</text><text
						class="answer-text">{{currentData.answer_b}}</text>
				</view>
				<view class="item" :class="correct.indexOf('C')>-1?'true':error.indexOf('C')>-1?'false':''"
					v-if="currentData.answer_c" @click="handleAnswer('C')">

					<text class="round" v-if="error.indexOf('C')>-1"><u-icon name="close" color="#fff"
							size="28"></u-icon></text>
					<text class="round" :class="multipleAnswer.indexOf('C')>-1?'selected':''" v-else>C</text><text
						class="answer-text">
						{{currentData.answer_c}}</text>
				</view>
				<view class="item" :class="correct.indexOf('D')>-1?'true':error.indexOf('D')>-1?'false':''"
					v-if="currentData.answer_d" @click="handleAnswer('D')">
					<text class="round" v-if="error.indexOf('D')>-1"><u-icon name="close" color="#fff"
							size="28"></u-icon></text>
					<text class="round" :class="multipleAnswer.indexOf('D')>-1?'selected':''" v-else>D</text><text
						class="answer-text">{{currentData.answer_d}}</text>
				</view>

			</view>
			<!-- 	<view class="skill" v-if="false">
				技巧：驾驶机动车发生事故阿斯利康久等啦可视角度拉进来，美年健康合适的科技风寒咳嗽交电话费.
			</view> -->

			<view class="detail" v-if="!isTrue">
				<view class="line">
					<view class="left"></view> 试题详解 <view class="left"></view>
				</view>
				<view class="standard">
					标准答案：{{explain}}
				</view>
			</view>
			<view class="confirm" @click="multiple"
				v-if="currentData.answer_c && currentData.right_answer.trim().length>1">
				提交
			</view>
			<view class="bottom">
				<view class="item" @click="prevSubject">
					<u-icon name="arrow-left"></u-icon>上一题
				</view>
				<view class="number" style="color: #4365C6;">
					<text class="round"> <u-icon name="checkmark"></u-icon></text>{{rightNum}}
				</view>
				<view class="number" style="color:#9A2925">
					<text class="round"> <u-icon name="close"></u-icon></text>{{errorNum}}
				</view>
				<view class="item" @click="linkPractice">
					<u-icon color="#3584FA" name="grid"></u-icon>{{thisNum+1}}/{{list.length}}
				</view>
				<view class="item" @click="nextSubject">
					下一题 <u-icon name="arrow-right"></u-icon>
				</view>
			</view>
		</view>
		<u-popup v-model="showNum" mode="bottom" @close="close" :closeable="true">

			<view class="popup-box">
				<scroll-view style="height:100%;height: 500rpx;" scroll-y @touchmove.stop
					:scroll-into-view="scrollIntoViewMenu">
					<view class="content-number">
						<view @click="getSortSubject(index)" class="item-number" v-for="(item,index) in countArray"
							:class="item.resoult===true?'active':item.resoult===false?'error':''" :key="index">
							{{index+1}}
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>
		<u-modal v-model="show" :content="content" @confirm="confirmModal" :show-cancel-button="true" cancel-text="返回"
			@cancel="cancel"></u-modal>
		<u-modal v-model="backShow" :content="hint" @confirm="confirmBack" :show-cancel-button="true" cancel-text="返回"
			@cancel="backShow=false"></u-modal>
	</view>
</template>

<script>
	import {
		mockexam,
		answerApi,
		randomNext,
		randomPrev,
		submitExam
	} from "@/api/index.js"
	import headChildren from '../../components/head.vue';
	export default {

		components: {
			headChildren
		},
		data() {
			return {
				scrollIntoViewMenu: '',
				countArray: [],
				showNum: false,
				hint: '您还没有做完所有题目确认返回放弃本次考试吗？',
				backShow: false,
				content: '',
				show: false,
				count: '',
				class: '',
				quest: '',
				subjectType: '',
				isTrue: true,
				explain: '',
				isAnswer: true,
				correct: '',
				error: '',
				thisNum: 0,
				multipleAnswer: '',
				resource: '',
				time: '',
				countdownDuration: '',
				endTime: '',
				currentData: '',
				exam_id: '',
				interval: null,
				errorNum: 0,
				rightNum: 0,
				list: [],
				numberArray: [],
				countDown: 2700, // 45分钟倒计时，单位为秒
				intervalId: null, // 计时器ID
			};
		},
		onLoad(option) {
			this.class = option.class
			this.subjectType = option.subjectType
			this.resource = option.resource
			if (this.subjectType == '1') {
				this.content = "模拟考试科目一是随机抽取100题进行考试，满分100分，90分及格，考试时间45分钟"
			} else {
				this.content = "模拟考试科目四是随机抽取50题进行考试，满分100分，90分及格，考试时间45分钟"
			}
		},
		mounted() {
			this.stopCountDown(); // 页面销毁前停止倒计时
			this.getSubject()
		},
		onBackPress(options) {
			this.stopCountDown(); // 页面销毁前停止倒计时
		},
		beforeDestroy() {
			this.stopCountDown(); // 页面销毁前停止倒计时
		},
		methods: {
			confirmBack() {
				uni.navigateBack()
			},
			close() {
				this.showNum = false
				// console.log('close');
			},
			//跳转
			linkPractice() {
				this.showNum = true
			},
			getSortSubject(index) {
				this.thisNum = index
				// this.error = ''
				this.correct = ''
				this.multipleAnswer = ''
				this.isTrue = true
				this.isAnswer = true
				this.currentData = this.list[this.thisNum]
				this.showNum = false
				this.automatic()
			},
			//自动填充答案
			automatic() {
				if (this.countArray[this.thisNum].found) {
					this.correct = this.currentData.right_answer
					let answer = this.countArray[this.thisNum].answer
					if (this.currentData.right_answer.length > 1) {
						if (this.multipleAnswer.indexOf(answer) > -1) {
							this.multipleAnswer = this.multipleAnswer.replace(new RegExp(answer, 'g'), '')
						} else {
							this.multipleAnswer += answer
						}
					} else {
						if (this.countArray[this.thisNum].resoult) {
							this.isTrue = true
							// this.rightNum++

						} else {
							this.explain = this.currentData.explain
							// this.errorNum++
							if (this.currentData.right_answer.length > 1) {
								for (let i in this.multipleAnswer) {
									if (this.correct.indexOf(this.multipleAnswer[i]) == -1) {
										this.error += this.multipleAnswer[i]
									}
								}
							} else {
								this.error = answer

							}
							this.isTrue = false
						}
					}
					console.log(this.multipleAnswer)
				} else {
					this.error = ''
				}
				console.log('this.error', this.error)
			},
			//判断底部渲染题目数量
			topicNum(answer) {
				let resoult = false
				if (answer === this.list[this.thisNum].right_answer) {
					resoult = true
				}
				this.numberArray.push(this.thisNum + 1)
				let bSet = new Set(this.numberArray);
				// 遍历a数组，并在找到的元素上添加'found'属性（但注意这会破坏数组的原始结构）
				for (let i = 0; i < this.countArray.length; i++) {
					if (bSet.has(this.countArray[i])) {
						this.countArray[i] = {
							value: this.countArray[i],
							found: true,
							answer,
							resoult
						}; // 注意这里我们替换了原始元素
					} else {
						// 如果不想替换原始元素，可以添加额外的属性，但这可能不是一个好的设计决策
						// a[i].found = false; // 这会引发错误，因为原始元素不是对象
					}
				}
			},
			//交卷
			btnSubmit() {
				let that = this
				if (this.numberArray.length < this.list.length) {
					wx.showModal({
						title: '提示',
						content: `已经做了${this.numberArray.length}题，还有${this.list.length-this.numberArray.length}题没做，确认要交卷嘛?`,
						success(res) {
							if (res.confirm) {
								that.pushExam()
							} else if (res.cancel) {
								console.log('用户点击取消')
							}
						}
					})
				} else {
					that.pushExam()
				}

			},
			//交卷接口
			pushExam(type) {
				let that = this
				submitExam({
					exam_id: this.exam_id
				}).then(res => {
					if (res.code == 1) {
						let hineText = ''
						if (type) {
							hineText = type
						}
						clearInterval(this.interval)
						wx.showModal({
							title: '',
							cancelText: '查看错题',
							confirmText: '返回首页',
							content: `${hineText}您的分数为${res.data.score}分`,
							success(res) {
								if (res.confirm) {
									uni.navigateBack(-1)
								} else if (res.cancel) {
									uni.redirectTo({
										url: "/pages/subject/errorLook"
									})
								}
							}
						})
					}
				})
			},
			//确认考试
			confirmModal() {
				this.startCountDown(); // 页面加载后开始倒计时
			},
			startCountDown() {
				this.intervalId = setInterval(() => {
					if (this.countDown > 0) {
						this.countDown--;
						// console.log('倒计时' + this.countDown);
					} else {
						this.stopCountDown(); // 倒计时结束时停止计时器
						console.log('倒计时结束');
						this.pushExam('考试时间结束')
					}
				}, 1000); // 每秒执行一次
			},
			stopCountDown() {
				clearInterval(this.intervalId); // 清除计时器
			},
			formatTime(seconds) {
				let minutes = Math.floor(seconds / 60);
				let secs = seconds % 60;
				minutes = minutes < 10 ? '0' + minutes : minutes;
				secs = secs < 10 ? '0' + secs : secs;
				return `${minutes}:${secs}`;
			},
			// 更新倒计时的显示
			// updateCountdown() {
			// 	const currentTime = Date.now();
			// 	const remainingTime = this.endTime - currentTime;
			// 	// 将毫秒转换为分钟和秒
			// 	const minutes = Math.floor((remainingTime % (1000 * 60 * 60)) / (1000 * 60));
			// 	const seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);
			// 	this.time = `${minutes} 分钟 ${seconds} 秒`
			// 	console.log(remainingTime)
			// 	if (remainingTime < 0) {
			// 		clearInterval(this.interval); // 倒计时结束时清除 interval
			// 		this.time = ''
			// 		this.pushExam('考试时间结束')
			// 	}
			// },
			//返回
			cancel() {
				uni.navigateBack()
			},
			//多选提交
			multiple() {
				this.getAnswer(this.multipleAnswer)
			},
			//点击答案
			handleAnswer(answer) {
				if (!this.thisNum && this.thisNum != 0) {
					uni.showToast({
						title: '出错了，请联系开发人员',
						icon: 'none'
					})

				}
				if (this.thisNum + 1 > this.countArray.length) {
					uni.showToast({
						title: '出错了，请联系客服',
						icon: 'none'
					})
				}
				if (this.countArray[this.thisNum].found) {
					return
				}
				//多选题
				if (this.currentData.right_answer.length > 1) {
					if (this.multipleAnswer.indexOf(answer) > -1) {
						this.multipleAnswer = this.multipleAnswer.replace(new RegExp(answer, 'g'), '')
					} else {
						this.multipleAnswer += answer
					}
				} else {
					this.getAnswer(answer)
				}
				console.log(this.multipleAnswer)
			},
			//答题
			getAnswer(answer) {
				if (!this.isAnswer) {
					return
				}
				this.topicNum(answer)
				let data = {
					exam_id: this.exam_id,
					question_id: this.currentData.id,
					answer: answer.split('').join(','),
					source: this.resource
				}
				this.correct = this.currentData.right_answer
				this.isAnswer = false
				answerApi(data).then(res => {
					if (res.code == 1) {
						this.isTrue = true
						this.rightNum++
						if (this.thisNum + 1 == this.list.length) {} else {
							setTimeout(() => {
								this.nextSubject()
							}, 800)
						}

					} else {
						this.explain = this.currentData.explain
						if (this.thisNum + 1 == this.list.length) {}
						this.errorNum++
						if (this.currentData.right_answer.length > 1) {
							for (let i in this.multipleAnswer) {
								if (this.correct.indexOf(this.multipleAnswer[i]) == -1) {
									this.error += this.multipleAnswer[i]
								}
							}
						} else {
							this.error = answer

						}
						this.isTrue = false
					}
				})
			},
			//下一题
			nextSubject() {
				if (this.thisNum == 99) {
					uni.showToast({
						title: '已经是最后一题了',
						icon: 'none'
					})
					return
				}
				this.thisNum++
				this.error = ''
				this.correct = ''
				this.multipleAnswer = ''
				this.isTrue = true
				this.isAnswer = true
				this.currentData = this.list[this.thisNum]
				this.automatic()

			},
			//上一题
			prevSubject() {
				if (this.thisNum == 0) {
					uni.showToast({
						title: '已经是第一题了',
						icon: 'none'
					})
					return
				}
				this.thisNum--
				this.error = ''
				this.correct = ''
				this.multipleAnswer = ''
				this.isTrue = true
				this.isAnswer = true
				this.currentData = this.list[this.thisNum]
				this.automatic()
			},
			//获取题目
			getSubject() {
				let params = {
					subject: this.subjectType,
				}
				mockexam(params).then(res => {
					if (res.code == 1) {
						if (res.data.list.length == 0) {
							uni.showToast({
								title: "当前没有题目可以考试",
								icon: "none"
							})
							setTimeout(() => {
								uni.navigateBack(-1)
							}, 2000)
						} else {
							this.isAnswer = true
							this.show = true
							this.list = res.data.list
							this.currentData = this.list[0]
							this.quest = res.data.question
							this.exam_id = res.data.exam_id
							this.countArray = Array.from({
								length: parseInt(this.list.length)
							}, (_, i) => i + 1)
						}

					}
				})
			},
		}
	}
</script>

<style lang="scss">
	.header {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		z-index: 9;
	}

	.main {
		position: relative;
	}

	.popup-box {
		width: 100%;
		height: 500rpx;
		padding: 20rpx 0;
	}

	.time {
		color: #fff;
	}

	.btn {
		color: #fff;
		font-size: 22rpx;

		position: absolute;
		right: 40rpx;
		top: 10rpx;
		z-index: 99999;

		.jiao {
			width: 32rpx;
			display: block;
			margin: 0 auto;
		}
	}

	.main {
		background-color: #fff;
		padding: 26rpx;
		padding-bottom: 150rpx;


		.confirm {
			font-size: 28rpx;
			color: #fff;
			background-color: #4394ED;
			position: absolute;
			right: 20rpx;
			bottom: 20%;
			border-radius: 100%;
			width: 100rpx;
			height: 100rpx;
			text-align: center;
			line-height: 100rpx;
		}

		.subject {
			font-size: 34rpx;
			color: #666;
			line-height: 50rpx;

			.type {
				color: #597CD6;
				border: 1px solid #597CD6;
				font-size: 34rpx;
				border-radius: 10rpx;
				padding: 2rpx 10rpx;
				margin-right: 10rpx;
			}
		}

		.images {
			margin-top: 40rpx;

			.img {
				width: 100%;
			}
		}

		.detail {
			margin-top: 40rpx;

			.line {
				display: flex;
				font-size: 28rpx;
				color: #C6362E;
				align-items: center;

				.left {
					border-bottom: 1px dotted #C6362E;
					height: 1px;
					flex: 1;
				}
			}

			.standard {
				color: #5F5F5F;
				font-size: 28rpx;
				margin-top: 20rpx;
			}
		}

		.answer {

			font-size: 30rpx;
			color: #000;

			.item {
				margin-top: 40rpx;
				display: flex;
				flex-wrap: wrap;

				.round {
					width: 50rpx;
					height: 50rpx;
					border-radius: 100%;
					border: 1px solid #333;
					display: block;
					text-align: center;
					line-height: 45rpx;
					font-size: 32rpx;
					margin-right: 10rpx;
				}

				.answer-text {
					flex: 1;
					font-size: 34rpx;
				}

				.selected {
					background-color: #333;
					color: #fff;
				}
			}

			.true {


				.round {
					background-color: #4394ED;
					color: #fff;
					border: 1px solid #4394ED;
				}
			}

			.false {
				.round {
					background-color: #D22E25;
					color: #fff;
					border: 1px solid #D22E25;
				}
			}
		}

		.other {
			display: flex;
			align-items: center;
			margin-top: 40rpx;

			.item {
				margin-right: 20rpx;
				color: #646464;
				padding: 10rpx 20rpx;
				border-radius: 10rpx;
				border: 1px solid #646464;
			}
		}

		.skill {
			margin-top: 40rpx;
			color: #333;
			line-height: 40rpx;
			font-size: 34rpx;
		}

		.bottom {
			position: fixed;
			bottom: 0;
			left: 0;
			background-color: #fff;
			display: flex;
			align-items: center;
			width: 100%;
			padding: 20rpx 10rpx;
			color: #5A5A5A;

			.item {
				flex: 1;
			}

			.number {
				flex: 1;

				.round {
					border: 1px solid #ccc;
					padding: 0 6rpx;
					margin-right: 4rpx;
				}
			}
		}
	}

	.content-number {
		padding: 40rpx;
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		padding-top: 100rpx;
		max-height: 500rpx;
		overflow: auto;
		-webkit-overflow-scrolling: touch;

		/* 支持iOS上的平滑滚动 */
		.item-number {
			width: 80rpx;
			height: 80rpx;
			margin-right: 30rpx;
			margin-bottom: 20rpx;
			border-radius: 100%;
			font-size: 24rpx;
			border: 1px solid #4394ED;
			text-align: center;
			line-height: 76rpx;
		}

		.active {
			background-color: #597CD6;
			color: #fff;

		}

		.error {
			background-color: #F3CA9E;
			border-color: #CB5B4D;
		}

		.item-number:nth-child(6n) {
			margin-right: 0;
		}
	}

	@media (min-width:500px) {
		.btn {
			right: calc(50% - 230px);
			margin-left: 250px;
		}
	}
</style>